#region Summary

// 
// Owner : JackieHan 
// 
// Solution : UpdateSystem 
// 
// Project : Skomart.Update.Download 
// 
// File : DownFile.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 下载文件
// 
// History : 
//			2010-08-02 11:17:55	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.IO;
using Skomart.Update.Config;
using Skomart.Update.Download.DownLoadService;

#endregion

namespace Skomart.Update.Download
{
    public delegate void DownloadStateChangedHandler(object sender, DownloadStateEventArgs eventArgs);

    /// <summary> 
    /// 下载文件
    /// </summary>
    public class DownloadFileManager
    {
        private readonly DownloadService downloadService;
        private readonly string systemDirectory;

        public event DownloadStateChangedHandler DownloadStateChanged;

        public DownloadFileManager()
        {
            downloadService = DownloadServiceManager.GetDownloadService();
            var baseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            if (baseDirectory.Parent != null) systemDirectory = baseDirectory.Parent.FullName;
        }

        /// <summary>
        /// 下载需要下载的文件
        /// </summary>
        /// <param name="updateFiles">需要下载的文件</param>
        /// <param name="systemName">系统名称</param>
        public void DownLoad(IList<HasUpdateFileInfo> updateFiles, string systemName)
        {
            long allUpdateFileLength = GetLength(updateFiles);
            if (allUpdateFileLength == 0)
                return;

            long hasDownLoadLength = 0;
            int index = 1;
            foreach (HasUpdateFileInfo hasUpdateFileInfo in updateFiles)
            {
                if (hasUpdateFileInfo.OperateType == OperateType.Delete)
                    continue;
                //检查文件夹是否存在，不存在创建文件夹
                var filePath = Path.Combine(systemDirectory, hasUpdateFileInfo.File);
                var fileInfo = new FileInfo(filePath);
                if ((fileInfo.Directory != null) && (!fileInfo.Directory.Exists))
                    fileInfo.Directory.Create();
                using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    var fileLength = hasUpdateFileInfo.FileLength;
                    if (fileLength == 0)
                        continue;
                    long offset = 0;
                    while (offset < fileLength)
                    {
                        var buffer = downloadService.GetFileByte(systemName, hasUpdateFileInfo.File, offset);
                        fileStream.Seek(offset, SeekOrigin.Begin);
                        long count = buffer.Length;
                        if (fileLength - offset < buffer.Length)
                            count = fileLength - offset;
                        fileStream.Write(buffer, 0, (int)count);
                        offset += count;

                        hasDownLoadLength += count;

                        //触发事件
                        var eventArgs = new DownloadStateEventArgs
                                            {
                                                AllDownloadPercent = (int)(hasDownLoadLength / allUpdateFileLength * 100),
                                                FileDownLoadPercent = (int)(offset / fileLength * 100),
                                                CurrentFileName = hasUpdateFileInfo.File,
                                                Discription =
                                                    string.Format("总共有{0}个文件需要下载,正在下载第{1}个文件......", updateFiles.Count,
                                                                  index)
                                            };
                        if (DownloadStateChanged != null)
                            DownloadStateChanged(this, eventArgs);
                    }
                }
                index++;
            }
        }

        private long GetLength(IList<HasUpdateFileInfo> updateFiles)
        {
            long lenght = 0;
            foreach (var hasUpdateFileInfo in updateFiles)
            {
                lenght += hasUpdateFileInfo.FileLength;
            }
            return lenght;
        }
    }
}